import axios from 'axios'
import { ElMessage } from 'element-plus'

// 获取当前页面类型（前台或后台）
function getCurrentContext() {
  const currentPath = window.location.pathname
  return currentPath.startsWith('/admin') ? 'admin' : 'user'
}

// 获取对应的token
function getContextToken() {
  const context = getCurrentContext()
  if (context === 'admin') {
    return localStorage.getItem('adminToken') || localStorage.getItem('token')
  } else {
    // 普通用户：优先获取userToken，然后尝试token作为后备
    return localStorage.getItem('userToken') || localStorage.getItem('token')
  }
}

// 创建axios实例
const service = axios.create({
  baseURL: '/api', // 使用代理路径
  timeout: 10000 // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 根据当前上下文获取对应的token
    const token = getContextToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    // 如果返回的状态码不是200，说明接口请求有问题
    if (res.code !== 200 && res.code !== undefined) {
      ElMessage({
        message: res.message || '请求失败',
        type: 'error',
        duration: 5 * 1000
      })
      
      // 处理特定错误码
      if (res.code === 401) {
        // 未登录或token过期 - 根据上下文清除对应token
        const context = getCurrentContext()
        if (context === 'admin') {
          localStorage.removeItem('adminToken')
          localStorage.removeItem('adminUserInfo')
          window.location.href = '/admin-login'
        } else {
          localStorage.removeItem('userToken')
          localStorage.removeItem('userUserInfo')
          window.location.href = '/login'
        }
      }
      
      return Promise.reject(new Error(res.message || '请求失败'))
    } else {
      return res
    }
  },
  error => {
    console.error('响应错误:', error)
    let message = error.message
    
    if (error.response) {
      switch (error.response.status) {
        case 401:
          message = '未授权，请重新登录'
          // 根据上下文清除对应token并跳转
          const context = getCurrentContext()
          if (context === 'admin') {
            localStorage.removeItem('adminToken')
            localStorage.removeItem('adminUserInfo')
            window.location.href = '/admin-login'
          } else {
            localStorage.removeItem('userToken')
            localStorage.removeItem('userUserInfo')
            window.location.href = '/login'
          }
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = `请求失败: ${error.message}`
      }
    }
    
    ElMessage({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    
    return Promise.reject(error)
  }
)

export default service 